﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Linq.Expressions;
using Newtonsoft.Json.Linq;

using CanDoo;
using CanDoo.Core;
using CanDoo.Data;
using CanDoo.Web;
using CanDoo.FineUI;
using CanDoo.Extensions;
using CanDoo.NPOI;
using CanDoo.Oil.Core.Models;
using CanDoo.Oil.Core.Contracts;
using CanDoo.Admin.Core.Contracts;
using FineUIPro;

namespace CanDoo.Oil.WebApp.storeSerialNumTemp
{
    public partial class ImportOut : PageBase
    {
        public ISerialNumContract SerialNumContract { get; set; }
        public IOilSerialNumContract OilSerialNumContract { get; set; }
        public ISerialNumTempContract SerialNumTempContract { get; set; }
        public IProductContract ProductContract { get; set; }

        public List<string> srcHeader1 = new List<string>();

        protected void Page_Load(object sender, EventArgs e)
        {
            srcHeader1.Add("序列号"); //0
            srcHeader1.Add("生产日期"); //3
            srcHeader1.Add("生产批次"); //4

            for (int j = 0; j < srcHeader1.Count; j++)
            {
                FineUIPro.BoundField column = Grid1.FindColumn("L" + j + "") as FineUIPro.BoundField;
                column.HeaderText = srcHeader1[j];
                column.DataField = srcHeader1[j];
                column.Hidden = false;
            }

            if (!IsPostBack)
            {
                if (Web.Request.QueryString("IS_RETRUN") != "")
                    btnClose.Hidden = false;
                btnSave.Enabled = false;
            }
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (!ed_File.HasFile)
            {
                Alert.ShowInTop("请先选择要上传的文件！");
            }
            string Path = System.Web.HttpContext.Current.Request.MapPath("~/UploadFiles/SerialNum/");

            string FileName = ed_File.FileName.Right(ed_File.FileName.Length - ed_File.FileName.LastIndexOf('\\') - 1);
            string NewFileName = RandomExtensions.RandFileName() + "_" + FileName;
            ed_File.SaveAs(Path + NewFileName);
            ed_filePath.SetValue(Path + NewFileName);

            System.Data.DataTable dt = NPOIHelper.Import(Path + NewFileName);
            if (dt.Rows.Count == 0)
            {
                Alert.ShowInTop("导入excel文件中没有任何数据");
                return;
            }
            var total = dt.Rows.Count;

            var header1 = NPOIHelper.GetRow(Path + NewFileName, 0);

            var msg = CheckTemplate(header1, srcHeader1);
            if (!msg.IsNull())
            {
                FineUIPro.Alert.ShowInTop(msg);
                return;
            }

            bool HaveError = false;
            for (int i = 0; i < total; i++)
            {
                for (int k = 0; k < srcHeader1.Count; k++)
                {
                    if (dt.Rows[i][srcHeader1[k]].ToString().Trim() == "")
                    {
                        if (srcHeader1[k] != "备注")
                        {
                            dt.Rows[i][srcHeader1[k]] = "<span style='color:red;font-weight:bold;'>不允许为空</span>";
                            HaveError = true;
                        }
                    }
                    else
                    {

                    }
                }
            }
            Grid1.DataSource = dt;
            Grid1.DataBind();
            if (!HaveError)
            {
                Alert.ShowInTop("数据通过校验，确认后，请点击导入按钮，完成导入！");
                btnSave.Enabled = true;
            }
            else
            {
                Alert.ShowInTop("部分数据匹配失败！，请注意红色部分！");
                btnSave.Enabled = false;
            }
        }

        private string CheckTemplate(List<string> header1, List<string> srcHeader1)
        {
            string msg = "";
            if (header1.Count != srcHeader1.Count)
            {
                ////done::模板不符合要求提示
                msg = "模板不对，建议使用给定的模板";
                return msg;
            }
            for (int i = 0; i < header1.Count; i++)
            {
                if (header1[i] != srcHeader1[i])
                {
                    ////done::模板不符合要求提示
                    msg += string.Format("模板不对，原因：字段不符合要求，现为 {0} ,应为 {1}</br>", header1[i], srcHeader1[i]);
                }
            }
            return msg;
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            System.Data.DataTable dt = NPOIHelper.Import(ed_filePath.GetValue().ToString());
            if (dt.Rows.Count == 0)
            {
                Alert.ShowInTop("导入excel文件中没有任何数据");
                return;
            }

            var total = dt.Rows.Count;

            var header1 = NPOIHelper.GetRow(ed_filePath.GetValue().ToString(), 0);

            var msg = CheckTemplate(header1, srcHeader1);
            if (!msg.IsNull())
            {
                FineUIPro.Alert.ShowInTop(msg);
                return;
            }
            var productId = Web.Request.QueryString("ProductId").ToLong(); ;
            var product = ProductContract.GetById(productId);
            if (product == null)
            {
                Alert.ShowInTop("参数错误！");
                return;
            }
            else
            {
                if (!product.ManageSerialNum)
                {
                    Alert.ShowInTop("此商品不需要管理序列号！");
                    return;
                }
            }

            try
            {
                var result = DB.Save(() => UpdateData(product,dt));
                Alert.ShowInTop(result.Message);
            }
            catch (Exception ee)
            {
                Alert.ShowInTop("导入失败！失败原因：" + ee.ToString(), "操作结果");
            }
        }

        public OperationResult UpdateData(Product product, System.Data.DataTable dt)
        {
            var wareHouseId = Web.Request.QueryString("WareHouseId").ToLong();
            OilSerialStatus state = OilSerialStatus.WaitOut;
            var outtype = Web.Request.QueryString("OutType").ToLong();
            if (outtype == 2559210030104576)
                state = OilSerialStatus.WaitBack;
            else if (outtype == 2558988965117952)
                state = OilSerialStatus.WaitBuyBack;

                var result = OperationResult.Success;

            if (product.ProductClass == 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    var serialNum = dt.Rows[i]["序列号"].ToString().Trim();
                    var m = SerialNumContract.Entities.FirstOrDefault(p => p.SerialNumber == serialNum);
                    if (m == null)
                    {
                        throw new Exception("序列号[" + dt.Rows[i]["序列号"].ToString().Trim() + "]不存在");
                    }
                    else
                    {
                        if(m.ProductId!=product.Id)
                            throw new Exception("序列号[" + dt.Rows[i]["序列号"].ToString().Trim() + "]和产品不匹配");
                        if(m.WarehouseId!= wareHouseId)
                            throw new Exception("序列号[" + dt.Rows[i]["序列号"].ToString().Trim() + "]的商品不在此仓库");

                        if (state == OilSerialStatus.WaitOut)
                        {
                            if (m.Status != 1)
                                throw new Exception("序列号[" + dt.Rows[i]["序列号"].ToString().Trim() + "]状态不允许出库");

                            m.OutStoreTypeId = Web.Request.QueryString("OutType").ToLong();
                            m.OutStoreId = Web.Request.QueryString("EntityId").ToLong();
                        }
                        else if (state == OilSerialStatus.WaitBack)
                        {
                            if (m.Status != 5)
                                throw new Exception("序列号[" + dt.Rows[i]["序列号"].ToString().Trim() + "]状态不允许销售退货");

                            m.OutSellBackId = Web.Request.QueryString("EntityId").ToLong();
                        }
                        else if (state == OilSerialStatus.WaitBuyBack)
                        {
                            if (m.Status != 1)
                                throw new Exception("序列号[" + dt.Rows[i]["序列号"].ToString().Trim() + "]状态不允许采购退货");
                            m.InBuyBackId = Web.Request.QueryString("EntityId").ToLong();
                        }
                        m.Status = (int)state;
                        SerialNumContract.UpdateEntity(m);
                    }
                }
            }
            else if (product.ProductClass == 1)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    var serialNum = dt.Rows[i]["序列号"].ToString().Trim();
                    var m = OilSerialNumContract.Entities.FirstOrDefault(p => p.SerialNumber == serialNum);
                    if (m == null)
                    {
                        throw new Exception("序列号[" + dt.Rows[i]["序列号"].ToString().Trim() + "]不存在");
                    }
                    else
                    {
                        
                        if (m.ProductId != product.Id)
                            throw new Exception("序列号[" + dt.Rows[i]["序列号"].ToString().Trim() + "]和产品不匹配");
                        if (m.WarehouseId != wareHouseId)
                            throw new Exception("序列号[" + dt.Rows[i]["序列号"].ToString().Trim() + "]的商品不在此仓库");

                        
                        if (state == OilSerialStatus.WaitOut)
                        {
                            if (m.Status != OilSerialStatus.PassIn)
                                throw new Exception("序列号[" + dt.Rows[i]["序列号"].ToString().Trim() + "]状态不允许出库");

                            m.OutStoreTypeId = Web.Request.QueryString("OutType").ToLong();
                            m.OutStoreId = Web.Request.QueryString("EntityId").ToLong();
                        }
                        else if (state == OilSerialStatus.WaitBack)
                        {
                            if (m.Status != OilSerialStatus.PassOut)
                                throw new Exception("序列号[" + dt.Rows[i]["序列号"].ToString().Trim() + "]状态不允许销售退货");

                            m.OutSellBackId = Web.Request.QueryString("EntityId").ToLong();
                        }
                        else if (state == OilSerialStatus.WaitBuyBack)
                        {
                            if (m.Status != OilSerialStatus.PassIn)
                                throw new Exception("序列号[" + dt.Rows[i]["序列号"].ToString().Trim() + "]状态不允许采购退货");
                            m.InBuyBackId = Web.Request.QueryString("EntityId").ToLong();
                        }

                        m.Status = state;
                        OilSerialNumContract.UpdateEntity(m);
                    }
                }
            }
            else if (product.ProductClass == 2)
            {

            }
            else
            {
                throw new Exception("产品参数错误");
            }

            return result;

        }
    }
}